package com.jinbei.restController;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.jinbei.common.Enum.ConstantsEnum;
import com.jinbei.common.annotation.AuthorAnnotation;
import com.jinbei.common.base.ResponseBase;
import com.jinbei.common.base.ResponseBaseEntity;
import com.jinbei.common.contants.Contants;
import com.jinbei.common.util.AuthorizationUtil;
import com.jinbei.common.util.CookieUtil;
import com.jinbei.common.util.TokenUtil;
import com.jinbei.domain.User;
import com.jinbei.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author zflu
 * 用户 restful 接口
 * Created by zflu on 2018/7/8.
 */
@RestController
@RequestMapping("/user")
public class UserController{

    private final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    /**   
     * @author zflu
     * @Description 查询用户
     * @date 2018/7/9 14:28
     * @param type  type 有 user 和 dept 区分查询单个人还是部门的人
     * @param id
     * @return com.jinbei.common.base.ResponseBase  
     */
    @AuthorAnnotation(name = "/user/queryUser" ,logs = "用户查询")
    @GetMapping("/queryUser")
    public ResponseBase queryUser(@RequestParam("type") String type,
                            @RequestParam("id") int id){
        try {
            Object result = null;
            //查询用户信息
            if(Contants.TYPE_USER.equals(type)){
                result = userService.queryUserByUserId(id);
            }else if(Contants.TYPE_DEPT.equals(type)){
                //根据部门id查询用户列表
                result = userService.queryUserListByDeptId(id);
            }
            return ResponseBaseEntity.setResultSuccess(result);
        }catch (Exception e){
            logger.error("查询用户详情失败!  {}",e);
            return ResponseBaseEntity.setResultError(null);
        }
    }

    /**
     * @author zflu
     * @Description   使用token查询用户信息
     * @date 2018/8/2 17:13
     * @param request
     * @return com.jinbei.common.base.ResponseBase
     */
    @AuthorAnnotation(name = "/user/queryUserByToken" ,logs = "用户Token查询")
    @GetMapping("/queryUserByToken")
    public ResponseBase queryUserByToken(HttpServletRequest request){
        try {
            JSONObject token = TokenUtil.getToken(request);
            if(token.isEmpty()){
                return ResponseBaseEntity.setResultError(ConstantsEnum.ERROR_501);
            }
            String loginName = (String) token.get(Contants.LOGIN_NAME);
            User user = userService.queryUserByLoginName(loginName);
            if(user != null){
                user.setPassword(null);
            }
            return ResponseBaseEntity.setResultSuccess(user);
        }catch (Exception e){
            logger.error("查询用户详情失败!  {}",e);
            return ResponseBaseEntity.setResultError(null);
        }
    }
    
    /**   
     * @author zflu
     * @Description 新增用户
     * @date 2018/7/9 14:29  
     * @param user
     * @return com.jinbei.common.base.ResponseBase  
     */
    @AuthorAnnotation(name = "/user/insertUser" ,logs = "用户新增")
    @PostMapping("/insertUser")
    public ResponseBase insertUser(@RequestBody User user){
        try {
            User queryUser = userService.queryUserByLoginName(user.getLoginName());
            if(queryUser != null){
                return ResponseBaseEntity.setResultError(ConstantsEnum.User_Error350);
            }
            int result = userService.insertUser(user);
            if(result > 0){
                return ResponseBaseEntity.setResultSuccess(Contants.BOOLEAN_TRUE);
            }else{
                return ResponseBaseEntity.setResultSuccess(Contants.BOOLEAN_FALSE);
            }
        }catch (Exception e){
            logger.error("新增用户失败!  {}",e);
            return ResponseBaseEntity.setResultError(null);
        }
    }

    /**
     * @author zflu
     * @Description 删除用户
     * @date 2018/7/9 14:29
     * @param userId
     * @return com.jinbei.common.base.ResponseBase
     */
    @AuthorAnnotation(name = "/user/deleteUser" ,logs = "用户删除")
    @DeleteMapping("/deleteUser")
    public ResponseBase deleteUser(@RequestParam("userId") int userId){
        try {
            int result = userService.deleteUserByUserId(userId);
            if(result > 0){
                return ResponseBaseEntity.setResultSuccess(Contants.BOOLEAN_TRUE);
            }else{
                return ResponseBaseEntity.setResultSuccess(Contants.BOOLEAN_FALSE);
            }
        }catch (Exception e){
            logger.error("删除用户失败!  {}",e);
            return ResponseBaseEntity.setResultError(null);
        }
    }

    /**
     * @author zflu
     * @Description 修改用户
     * @date 2018/7/9 14:34
     * @param user
     * @return com.jinbei.common.base.ResponseBase
     */
    @AuthorAnnotation(name = "/user/updateUser" ,logs = "用户修改")
    @PutMapping("/updateUser")
    public ResponseBase updateUser(@RequestBody User user){
        try {
            int result = userService.updateUser(user);
            if(result > 0){
                return ResponseBaseEntity.setResultSuccess(Contants.BOOLEAN_TRUE);
            }else{
                return ResponseBaseEntity.setResultSuccess(Contants.BOOLEAN_FALSE);
            }
        }catch (Exception e){
            logger.error("更新用户失败!  {}",e);
            return ResponseBaseEntity.setResultError(null);
        }
    }

    /**
     * @author zflu
     * @Description 更新用户锁定状态
     * @date 2018/7/9 15:05
     * @param userId
     * @return com.jinbei.common.base.ResponseBase
     */
    @AuthorAnnotation(name = "/user/lockUser" ,logs = "更新用户锁定状态")
    @PutMapping("/lockUser")
    public ResponseBase lockOrUnLockUser(@RequestParam("userId") int userId){
        try {
            int result = userService.lockOrUnLockUser(userId);
            if(result > 0){
                return ResponseBaseEntity.setResultSuccess(Contants.BOOLEAN_TRUE);
            }else{
                return ResponseBaseEntity.setResultSuccess(Contants.BOOLEAN_FALSE);
            }
        }catch (Exception e){
            logger.error("更新用户锁定状态失败!  {}",e);
            return ResponseBaseEntity.setResultError(null);
        }
    }

    /**
     * @author zflu
     * @Description   查询用户分页列表
     * @date 2018/7/11 17:16
     * @param pageNum, pageSize
     * @return com.jinbei.common.base.ResponseBase
     */
    @AuthorAnnotation(name = "/user/queryUserPage" ,logs = "用户分页查询")
    @GetMapping("/queryUserPage")
    public ResponseBase queryUserPage(@RequestParam("pageNum") int pageNum,
                                      @RequestParam("pageSize") int pageSize ){
        try {
            PageInfo pageInfo = userService.queryUserPage(pageNum, pageSize);
            return ResponseBaseEntity.setResultSuccess(pageInfo);
        }catch (Exception e){
            logger.error("查询用户分页列表失败!  {}",e);
            return ResponseBaseEntity.setResultError(null);
        }
    }

    /**
     * @author zflu
     * @Description    修改用户密码
     * @date 2018/8/3 11:26
     * @param map
     * @return com.jinbei.common.base.ResponseBase
     */
    @AuthorAnnotation(name = "/user/updateUserPassword" ,logs = "用户密码修改")
    @PutMapping("/updateUserPassword")
    public ResponseBase updateUserPassword(@RequestBody Map<String,String> map){
        try {
            int result = userService.updateUserPassword(map);
            if(result > 0){
                return ResponseBaseEntity.setResultSuccess(Contants.BOOLEAN_TRUE);
            }else{
                return ResponseBaseEntity.setResultSuccess(Contants.BOOLEAN_FALSE);
            }
        }catch (Exception e){
            logger.error("修改用户密码失败!  {}",e);
            return ResponseBaseEntity.setResultError(null);
        }
    }


    /**
     * @author zflu
     * @Description   校验用户密码
     * @date 2018/8/3 16:16
     * @param map, request
     * @return com.jinbei.common.base.ResponseBase
     */
    @AuthorAnnotation(name = "/user/checkPassword" ,logs = "用户校验密码")
    @PostMapping("/checkPassword")
    public ResponseBase checkPassword(@RequestBody Map<String,String> map
            ,HttpServletRequest request){
        String password = map.get(Contants.PASSWORD);
        try {
            JSONObject token = TokenUtil.getToken(request);
            if(token.isEmpty()){
                return ResponseBaseEntity.setResultError(ConstantsEnum.ERROR_501);
            }
            String loginName = (String) token.get(Contants.LOGIN_NAME);
            User user = userService.queryLoginUser(loginName,password);
            if(user != null){
                return ResponseBaseEntity.setResultSuccess(Contants.BOOLEAN_TRUE);
            }else{
                return ResponseBaseEntity.setResultSuccess(Contants.BOOLEAN_FALSE);
            }
        }catch (Exception e){
            logger.error("校验用户密码失败!  {}",e);
            return ResponseBaseEntity.setResultError(null);
        }
    }

    /**
     * @author zflu
     * @Description   用户权限修改
     * @date 2018/8/7 13:33
     * @param map
     * @return com.jinbei.common.base.ResponseBase
     */
    @AuthorAnnotation(name = "/user/updateUserRoles" ,logs = "用户权限修改")
    @PutMapping("/updateUserRoles")
    public ResponseBase updateUserRoles(@RequestBody Map<String,String> map){
        try {
            int result = userService.updateUserRoles(map);
            if(result > 0){
                return ResponseBaseEntity.setResultSuccess(Contants.BOOLEAN_TRUE);
            }else{
                return ResponseBaseEntity.setResultSuccess(Contants.BOOLEAN_FALSE);
            }
        }catch (Exception e){
            logger.error("用户权限修改失败!  {}",e);
            return ResponseBaseEntity.setResultError(null);
        }
    }

}
